/*
 * Copyright © 2004-2014 chenYuan. All rights reserved.
 * @Website:wwww.jspx.net
 * @Mail:39793751@qq.com
 * @author: chenYuan , 陈原
 * @License: Jspx.net Framework Code is open source (LGPL)，Jspx.net Framework 使用LGPL 开源授权协议发布。
 * @jvm:jdk1.6+  x86/amd64
 *
 */
package com.jspx.txweb.view;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import com.jspx.txweb.annotation.HttpMethod;
import com.jspx.txweb.annotation.Safety;
import com.jspx.txweb.env.TXWeb;
import com.jspx.txweb.support.ActionSupport;
import com.jspx.txweb.util.RequestUtil;
import com.jspx.txweb.util.ValidateCode;

/**
 * Created by IntelliJ IDEA.
 * User:chenYuan (mail:39793751@qq.com)
 * Date: 2006-3-31
 * Time: 22:56:19
 */
@HttpMethod(caption = "验证图片")
public class ValidateImgView extends ActionSupport {

    public ValidateImgView() {

    }

    // 图片的宽度。
    private int width = 76;
    // 图片的高度。
    private int height = 25;
    // 验证码干扰线数
    private int lineCount = 20;

    private int length = 5;

    private String fileType = "png";

    private boolean safe = true;


    public int getWidth() {
        return width;
    }

    @Safety
    public void setWidth(int width) {
        this.width = width;
    }

    public int getHeight() {
        return height;
    }

    @Safety
    public void setHeight(int height) {
        this.height = height;
    }

    @Safety(request = false)
    public void setLineCount(int lineCount) {
        this.lineCount = lineCount;
    }

    public int getLength() {
        return length;
    }

    @Safety(request = false)
    public void setLength(int length) {
        this.length = length;
    }

    @Safety(request = false)
    public void setSafe(boolean safe) {
        this.safe = safe;
    }

    @Safety(request = false)
    public void setFileType(String fileType) {
        this.fileType = fileType;
    }


    public String execute() throws Exception {
        if (safe&& RequestUtil.isPirated(request))
        {
            return NONE;
        }
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/" + fileType);
        ValidateCode validateCode = new ValidateCode(width, height, length, lineCount);
        String code = validateCode.makeCode();
        ServletOutputStream out = response.getOutputStream();
        try {
            session.setAttribute(TXWeb.jspxValidate, code);
            session.setAttribute(TXWeb.jspxValidateTime, System.currentTimeMillis());
            ImageIO.write(validateCode.getBufferImage(), fileType, out);
            out.flush();
        } finally {
            if (out!=null)
                out.close();
        }
        return NONE;
    }
}